(function(){
  // UI elements
  const apiUrlEl = document.getElementById('apiUrl');
  const apiKeyEl = document.getElementById('apiKey');
  const saveCfgBtn = document.getElementById('saveCfg');
  const saveStatus = document.getElementById('saveStatus');

  const fileInput = document.getElementById('fileInput');
  const dropzone = document.getElementById('dropzone');
  const uploadBtn = document.getElementById('uploadBtn');
  const showSel = document.getElementById('show');
  const pwdInput = document.getElementById('pwd');
  const uploadList = document.getElementById('uploadList');
  const historyList = document.getElementById('historyList');
  const refreshHistory = document.getElementById('refreshHistory');
  const clearHistory = document.getElementById('clearHistory');

  // tabs
  document.querySelectorAll('.tab-btn').forEach(btn=>{
    btn.addEventListener('click', ()=>{
      document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
      document.querySelectorAll('.tab').forEach(t=>t.classList.remove('active'));
      btn.classList.add('active');
      document.getElementById('tab-'+btn.dataset.tab).classList.add('active');
    });
  });

  let cfg = { apiUrl: '', apiKey: '' };
  const MAX_HISTORY = 200;

  const errorMap = {
    0: '成功',
    '-1': '请求或存储/数据库失败',
    '-2': 'apikey 无效或用户不存在/已禁用',
    '-3': '缺少 apikey 参数',
    '-4': '请求方法不允许 / 未开启API / 来源地址不正确',
    '-5': '用户表缺少 api_key 字段（部署问题）'
  };

  function loadConfig(){
    return new Promise(resolve => {
      chrome.storage.sync.get(["apiUrl", "apiKey"], (items) => {
        cfg.apiUrl = items.apiUrl || '';
        cfg.apiKey = items.apiKey || '';
        apiUrlEl.value = cfg.apiUrl;
        apiKeyEl.value = cfg.apiKey;
        ensureCfg();
        resolve(cfg);
      });
    });
  }

  function saveConfig(){
    const url = (apiUrlEl.value||'').trim();
    const key = (apiKeyEl.value||'').trim();
    chrome.storage.sync.set({ apiUrl: url, apiKey: key }, ()=>{
      cfg.apiUrl = url; cfg.apiKey = key;
      saveStatus.textContent = '已保存';
      setTimeout(()=> saveStatus.textContent='', 1500);
      ensureCfg();
    });
  }

  function ensureCfg(){
    const ok = !!(cfg.apiUrl && cfg.apiKey);
    uploadBtn.disabled = !(ok && fileInput.files && fileInput.files.length);
    return ok;
  }

  function setDragging(on){ dropzone.classList.toggle('dragging', !!on); }

  function escapeHtml(str){ const d=document.createElement('div'); d.textContent=str; return d.innerHTML; }
  function formatSize(bytes){ const units=['B','KB','MB','GB']; let i=0,val=bytes; while(val>1024&&i<units.length-1){ val/=1024; i++; } return (Math.round(val*10)/10)+' '+units[i]; }

  function createItemCard(file){
    const card = document.createElement('div');
    card.className = 'upload-item';
    card.innerHTML = `
      <div class="meta">
        <div class="name">${escapeHtml(file.name)}</div>
        <div class="size">${formatSize(file.size)}</div>
      </div>
      <div class="progress"><div class="bar" style="width:0%"></div></div>
      <div class="status">
        <span class="code muted">待上传</span>
        <div class="links"></div>
      </div>`;
    return card;
  }

  function pushHistory(entry){
    chrome.storage.sync.get(["history"], (items)=>{
      const list = items.history || [];
      list.unshift(entry);
      while(list.length > MAX_HISTORY) list.pop();
      chrome.storage.sync.set({ history: list });
    });
  }

  function renderHistory(){
    chrome.storage.sync.get(["history"], (items)=>{
      const list = items.history || [];
      historyList.innerHTML = '';
      if(!list.length){ historyList.innerHTML = '<p class="muted">暂无历史记录</p>'; return; }
      list.forEach(it=>{
        const row = document.createElement('div');
        row.className = 'history-item';
        const codeText = errorMap[String(it.code)] || ('code=' + it.code);
        row.innerHTML = `
          <div class="meta">
            <div class="name">${escapeHtml(it.name || '')}</div>
            <div class="sub muted">${new Date(it.time).toLocaleString()} · ${formatSize(it.size||0)} · ${codeText}</div>
          </div>
          <div class="links"></div>`;
        const links = row.querySelector('.links');
        if(it.downurl){ const a=document.createElement('a'); a.href=it.downurl; a.target='_blank'; a.textContent='下载'; links.appendChild(a); const b=document.createElement('button'); b.className='btn'; b.textContent='复制下载'; b.onclick=()=>navigator.clipboard.writeText(it.downurl); links.appendChild(b); }
        if(it.viewurl){ const a=document.createElement('a'); a.href=it.viewurl; a.target='_blank'; a.textContent='预览'; links.appendChild(a); const b=document.createElement('button'); b.className='btn'; b.textContent='复制预览'; b.onclick=()=>navigator.clipboard.writeText(it.viewurl); links.appendChild(b); }
        historyList.appendChild(row);
      });
    });
  }

  function xhrUpload(file, opts){
    return new Promise((resolve)=>{
      const xhr = new XMLHttpRequest();
      xhr.open('POST', cfg.apiUrl);
      xhr.setRequestHeader('X-API-Key', cfg.apiKey);
      const fd = new FormData();
      fd.append('file', file);
      fd.append('apikey', cfg.apiKey);
      fd.append('show', String(opts.show));
      if(opts.pwd){ fd.append('ispwd','1'); fd.append('pwd', opts.pwd); }
      xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ try{ resolve(JSON.parse(xhr.responseText)); } catch(e){ resolve({ code:-1, msg:'解析失败', error:String(e) }); } } };
      xhr.upload.onprogress = function(e){ if(e.lengthComputable){ opts.onProgress(Math.round(e.loaded/e.total*100)); } };
      xhr.onerror = function(){ resolve({ code:-1, msg:'网络错误' }); };
      xhr.send(fd);
    });
  }

  async function doUploadBatch(){
    await loadConfig();
    if(!ensureCfg()){ alert('请先保存 API 地址与密钥'); return; }
    const files = Array.from(fileInput.files || []);
    if(!files.length){ alert('请选择文件'); return; }

    uploadList.innerHTML = '';
    const show = showSel.value === '1' ? 1 : 0;
    const pwd = (pwdInput.value||'').trim();

    for(const file of files){
      const card = createItemCard(file);
      uploadList.appendChild(card);
      const bar = card.querySelector('.bar');
      const codeEl = card.querySelector('.code');
      const linksEl = card.querySelector('.links');

      codeEl.textContent = '上传中...';
      uploadBtn.disabled = true;

      const res = await xhrUpload(file, { show, pwd, onProgress: (pct)=>{ bar.style.width = pct + '%'; } });

      const codeText = errorMap[String(res.code)] || ('code=' + res.code);
      codeEl.textContent = codeText + (res.msg ? (' · ' + res.msg) : '');

      if(res.downurl){ const a1 = document.createElement('a'); a1.href = res.downurl; a1.target = '_blank'; a1.textContent = '下载地址'; linksEl.appendChild(a1); const b1 = document.createElement('button'); b1.className='btn'; b1.textContent='复制下载'; b1.onclick = ()=> navigator.clipboard.writeText(res.downurl); linksEl.appendChild(b1); }
      if(res.viewurl){ const a2 = document.createElement('a'); a2.href = res.viewurl; a2.target = '_blank'; a2.textContent = '预览地址'; linksEl.appendChild(a2); const b2 = document.createElement('button'); b2.className='btn'; b2.textContent='复制预览'; b2.onclick = ()=> navigator.clipboard.writeText(res.viewurl); linksEl.appendChild(b2); }

      pushHistory({ time: Date.now(), name: file.name, size: file.size, code: res.code, msg: res.msg, downurl: res.downurl, viewurl: res.viewurl });
      uploadBtn.disabled = false;
    }
  }

  // drag & drop
  dropzone.addEventListener('dragenter', e=>{ e.preventDefault(); setDragging(true); });
  dropzone.addEventListener('dragover', e=>{ e.preventDefault(); });
  dropzone.addEventListener('dragleave', e=>{ e.preventDefault(); setDragging(false); });
  dropzone.addEventListener('drop', e=>{ e.preventDefault(); setDragging(false); const items=e.dataTransfer.files; if(items&&items.length){ fileInput.files = items; ensureCfg(); }});

  // events
  fileInput.addEventListener('change', ()=> ensureCfg());
  uploadBtn.addEventListener('click', doUploadBatch);
  saveCfgBtn.addEventListener('click', saveConfig);
  refreshHistory.addEventListener('click', renderHistory);
  clearHistory.addEventListener('click', ()=> chrome.storage.sync.set({history: []}, renderHistory));

  // init
  loadConfig().then(()=> ensureCfg());
  renderHistory();
})();